/**
 * Created by duanxiancai on 2017/1/12.
 */
function loadScript(url, callback){
    var script = document.createElement ("script");
    script.type = "text/javascript";
    if (script.readyState){ //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" || script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else { //Others
        script.onload = function(){
            callback();
        };
    }
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}
function indexJsLoad() {
    loadScript("js/mui.min.js",function () {
        loadScript("js/jquery.min.js",function () {
            loadScript("js/vdTool.js",function () {
                loadScript("js/jqRequest.js",function () {
                    loadScript("js/webViewJsBridge.js",function () {
                        loadScript("js/fastclick.js",function () {
                            var localDebug = false;
                            //页面参数
                            var num = 1;
                            var limitNum = 0;
                            var detailTypeSeleted = 1;
                            //请求回调数据
                            var response; var types;var keys;
                            //已选择
                            var seletedTypes = [];var babyInfo;var typeLength = 0;var isNative = 0;
                            var indexParams = getParams();//type:幸福直通车：1-1 四点半课堂：1-2 健康体检 ：2-1 健康食堂：2-2
                            var indexBridge;
                            indexBridgeInit(indexParams.clientType,function (bridge) {
                                indexBridge = bridge;
                                bridge.registerHandler('sendInfoToWeb', function(data, responseCallback) {
                                    //android的为啥和还要转json
                                    babyInfo = strToJson(data);
                                    jq(".selectDataArrowCell .seletedContent").html(babyInfo["name"]);
                                });
                            });
                            var jq=jQuery.noConflict();
                            //初始化loading
                            loadingInit('img/loading.gif');

                            jq(function () {
                                FastClick.attach(document.body);//处理移动端click问题
                                indexLayout();
                                //监听浏览器窗口变化
                                window.onresize=function(){
                                    indexLayout();
                                };
                                jq("#infoSeletedCell").click(function () {
                                    selectedDetail();
                                })
                            });

                            //适配
                            function indexLayout() {
                                var h = window.innerHeight - 44;
                                jq(".contentView").css({
                                    "height":h+'px'
                                });
                                jq("#detail").css({
                                    "height":h+'px'
                                });
                                jq("#detailContent").addClass('alpha-noScroll');
                                jq('#firstContent').scroll(function(){
                                    if(jq(this).scrollTop() >= jq('#topTableView').height()+10) {
                                        detailTypeSeleted = 0;
                                        jq("#detailContent").removeClass('alpha-noScroll');
                                    }else {
                                        detailTypeSeleted ++;
                                        if (detailTypeSeleted == 1){
                                            jq("#detailContent").addClass('alpha-noScroll');
                                        }
                                    }
                                });
                            }
                            //request
                            function indexPageDataRequest() {
                                sendRequest('getBlissWeb',{"type":indexParams.type},function (data) {
                                    response = data;
                                    types = data["data"];
                                    keys = getJsonKeys(types);
                                    //初始化banner
                                    var pics = [];
                                    pics = response["picurls"];
                                    initbanner(pics);
                                    //赋值
                                    jq(".indexTitle").html(data["serviceName"]);
                                    jq(".indexInfo").html(data["prmoteDes"]);
                                    jq(".infoTitle").html(data["serviceName"]);
                                    jq(".indexMark").html(data["nowPriceStr"]);
                                    jq(".indexNewPrice").html('￥'+data["nowPrice"]);
                                    jq(".indexOldPrice").html('原价￥'+data["orginalPrice"]);
                                    jq(".infoPrice").html('￥'+data["nowPrice"]);
                                    jq(".infoIndexIcon").attr("src",data["icon"]);
                                    //详情页
                                    prepareDetail();
                                    //规格添加
                                    jq.each(keys,function (i,key) {
                                        appendTypeCell(i,key);
                                    });
                                    //数量选择添加
                                    jq(".typeSelecteContent").append('<div class="mui-table-view-cell typeContent"> <div class="numSelecterContent"> <div class="numMark"> 购买数量 </div> <div class="numSelecter"> <img class="reduce" src="img/icon_minus_grey.png" onclick="changeNum(-1)"> <div id="num"> 1 </div> <img class="plus" src="img/icon_plus_red.png" onclick="changeNum(1)"> </div> </div> <div class="limitNumDiv"> 每位用户限购<span class="limitNum">'+limitNum+'</span>件 </div> </div>');
                                    jq(".limitNumDiv").hide();
                                    addTypeSeletedAction();
                                });
                            }
                            function getUserTimesRequest(item) {
                                sendRequest('getBlissLimitNum',{"token":indexParams.token,"blissDictionartType":item["type"]},function (data) {
                                    var usedTimes = data["limitnum"];//已购次数
                                    limitNum = item["limited"] - usedTimes;
                                    if (limitNum > 0){
                                        jq(".limitNumDiv").show();
                                        if (limitNum == 1){
                                            jq(".plus").attr("src","img/icon_plus_grey.png");
                                        }
                                    }else {
                                        jq(".limitNumDiv").hide();
                                    }
                                    jq(".limitNum").html(limitNum);
                                });
                            }
                            function submitInfoRequest() {
                                startLoading();
                                var outhersId = 0;
                                if (isNative == 1){
                                    outhersId = babyInfo["id"];
                                }
                                var dictoinatyId = seletedTypes[0]["id"];
                                var dictionaryTypes = '';
                                jq.each(seletedTypes,function (idx,item) {
                                    if (dictionaryTypes == ''){
                                        dictionaryTypes = dictionaryTypes + item["type"];
                                    }else {
                                        dictionaryTypes = dictionaryTypes+'/'+item["type"];
                                    }

                                });
                                sendRequest('addBlissService',{"type":indexParams.type,"statue":response["statue"],"outhersId":outhersId,"dictoinatyId":dictoinatyId,"dictionaryTypes":dictionaryTypes,"num":num},function (data) {
                                    stopLoading();
                                    indexBridge.callHandler('submitOrderInfo',data["blissServiceId"]);
                                })
                            }
                            indexPageDataRequest();
                            if (localDebug == true){
                                getJsonData("goodsDetail.json",function (data) {
                                    response = data;
                                    types = data["data"];
                                    keys = getJsonKeys(types);
                                    //初始化banner
                                    var pics = [];
                                    pics = response["picurls"];
                                    initbanner(pics);
                                    //赋值
                                    jq(".indexTitle").html(data["serviceName"]);
                                    jq(".indexInfo").html(data["prmoteDes"]);
                                    jq(".infoTitle").html(data["serviceName"]);
                                    jq(".indexMark").html(data["nowPriceStr"]);
                                    jq(".indexNewPrice").html('￥'+data["nowPrice"]);
                                    jq(".indexOldPrice").html('原价￥'+data["orginalPrice"]);
                                    jq(".infoPrice").html('￥'+data["nowPrice"]);
                                    jq(".infoIndexIcon").attr("src",data["icon"]);
                                    //详情页
                                    prepareDetail();
                                    //规格添加
                                    jq.each(keys,function (i,key) {
                                        appendTypeCell(i,key);
                                    });
                                    //数量选择添加
                                    jq(".typeSelecteContent").append('<div class="mui-table-view-cell typeContent"> <div class="numSelecterContent"> <div class="numMark"> 购买数量 </div> <div class="numSelecter"> <img class="reduce" src="img/icon_minus_grey.png" onclick="changeNum(-1)"> <div id="num"> 1 </div> <img class="plus" src="img/icon_plus_red.png" onclick="changeNum(1)"> </div> </div> <div class="limitNumDiv"> 每位用户限购<span class="limitNum">'+limitNum+'</span>件 </div> </div>');
                                    jq(".limitNumDiv").hide();
                                    addTypeSeletedAction();
                                });
                            }
                            //初始化banner
                            function initbanner(pics) {
                                var len = pics.length;
                                var banners = '<div class="mui-slider"> <div id="indexBanner" class="mui-slider-group mui-slider-loop">';
                                var imgs = '<div class="mui-slider-item"><img src="'+pics[len-1]+'" /></div>';
                                var jj = '</div> <div id="indexBanner-indicator" class="mui-slider-indicator">';
                                var gg = '</div> </div>';
                                var indicators = '';
                                jq.each(pics,function (idx,url) {
                                    imgs = imgs + '<div class="mui-slider-item"><img src="'+url+'" /></div>';
                                    if (idx == 0){
                                        indicators = indicators + '<div class="mui-indicator mui-active"></div>';
                                    } else {
                                        indicators = indicators + '<div class="mui-indicator"></div>';
                                    }
                                });
                                imgs = imgs + '<div class="mui-slider-item"><img src="'+pics[0]+'" /></div>';
                                banners = banners + imgs + jj + indicators + gg;
                                jq("#bannerCell").append(banners);
                                //获得slider插件对象
                                var gallery = mui('.mui-slider');
                                gallery.slider({
                                    interval:0//自动轮播周期，若为0则不自动播放，默认为0；
                                });
                            }
                            //动态添加规格
                            function appendTypeCell(idx,key) {
                                var arr = types[key];
                                var cell = '';
                                if (arr.length <= 0||arr == undefined){
                                    isNative = 1;
                                    cell = cell+'<div class="typeContent"><div class="selectDataArrowCell"> <div class="title"> '+key+ '</div> <div class="seletedContent"></div> <img src="img/wode_list_go.png"> </div></div>';
                                }else {
                                    typeLength ++;
                                    cell = '<div class="typeContent"> <div class="typeTitle">'+key+'</div>';
                                    jq.each(arr,function (i,ite) {
                                        var item ='<div id="'+idx+'-'+i+'" class="typeCell normal"> <p>'+ite["name"]+'</p> </div>';
                                        cell = cell+item;
                                    });
                                    cell = cell+'</div>';
                                }
                                jq(".typeSelecteContent").append(cell);
                            }
                            //点击事件
                            function selectedDetail() {
                                jq(".infoSeletedContent").fadeIn();
                                jq(".infoContent").animate({bottom:'0px'});
                                jq("#firstContent").addClass('alpha-noScroll');
                                jq("html").addClass('alpha-noScroll');
                            }
                            jq(".infoClose").on("click",function () {
                                jq(".infoSeletedContent").fadeOut();
                                jq(".infoContent").animate({bottom:'-424px'});
                                jq("#firstContent").removeClass('alpha-noScroll');
                                jq("html").removeClass('alpha-noScroll');
                            });
                            jq(".bottomButton").on("click",function () {
                                if (seletedTypes.length == typeLength && isNative == 0){
                                    submitInfoRequest();
                                }
                                 else if (seletedTypes.length == typeLength && babyInfo !=undefined && babyInfo != null){
                                    submitInfoRequest();
                                }else {
                                    selectedDetail();
                                    indexBridge.callHandler('toast','请完善规格信息');
                                }

                            });
                            //选择规格
                            function addTypeSeletedAction() {
                                jq(".typeCell").on("click",function () {
                                    //改变他的兄弟姐妹
                                    var bro = jq(this).siblings(".typeCell");
                                    jq(bro).removeClass("selected");
                                    jq(bro).addClass("normal");

                                    jq(this).addClass('selected');
                                    jq(this).removeClass('normal');

                                    //对id进行分割处理 获取选择的规格所在的行和列
                                    var thisId = jq(this).attr("id");
                                    var arr = thisId.split('-');
                                    var section = parseInt(arr[0]);
                                    var row = parseInt(arr[1]);
                                    var minTypes = types[keys[section]];
                                    var item = minTypes[row];
                                    console.info(item);
                                    //只有在第一行的规格才会改变限购数
                                    if (section == 0){
                                        //限购数
                                        getUserTimesRequest(item);
                                        //价格
                                        jq(".indexNewPrice").html('￥'+item["nowprice"]/100+'元/'+item["unit"]);
                                        jq(".indexOldPrice").html('原价￥'+item["orginalprice"]/100+'元/'+item["unit"]);
                                        jq(".infoPrice").html('￥'+item["nowprice"]/100+'元/'+item["unit"]);
                                    }
                                    seletedTypes[section] = item;
                                    var desc = '已选:';
                                    jq.each(seletedTypes,function (idx,model) {
                                        if (model != undefined){
                                            if (desc == '已选:'){
                                                desc = desc + model['name'];
                                            }else {
                                                desc = desc + '/' + model['name'];
                                            }

                                        }
                                    });
                                    jq('.indexSelectedMark').html(desc);
                                });
                                jq(".selectDataArrowCell").on("click",function () { 
                                    indexBridge.callHandler("getData", "babyInfo", function(resp) {
                                        babyInfo = resp;
                                        jq(".selectDataArrowCell .seletedContent").html(babyInfo.name);
                                    });
                                });
                                jq(".plus").on("click",function () {
                                    changeNum(1);
                                });
                                jq(".reduce").on("click",function () {
                                    changeNum(-1);
                                });
                            }
                            //加减
                            function changeNum(v) {
                                var changedNum = num + v;
                                if (changedNum == 1){
                                    jq(".reduce").attr("src","img/icon_minus_grey.png");
                                }else if (limitNum !=0 && changedNum >= limitNum) {
                                    changedNum = limitNum;
                                    jq(".plus").attr("src","img/icon_plus_grey.png");
                                }else if (changedNum > 1) {
                                    jq(".reduce").attr("src","img/icon_minus_red.png");
                                    jq(".plus").attr("src","img/icon_plus_red.png");
                                }else {
                                    changedNum = 1;
                                }
                                num = changedNum;
                                jq("#num").html(num);
                            }
                            function prepareDetail() {
                                var detailPage;var detailType = 0;
                                var evaluatePage;
                                function loadDetailPage() {
                                    if (detailPage){
                                        jq("#detailContent").html(detailPage);
                                    }else {
                                        jq.get(response["detail"],function(data){
                                            detailPage = data;
                                            if (detailType == 0){
                                                jq("#detailContent").html(detailPage);
                                            }
                                        });
                                    }
                                }
                                loadDetailPage();
                                // jq("#detailContent").html('<iframe src="'+response["detail"]+'"></iframe>');
                                var h = window.innerHeight - 44 * 2 - 10;
                                jq("#detailContent").css({
                                    "height":h+'px'
                                });
                                //监听浏览器窗口变化
                                window.onresize=function(){
                                    var h = window.innerHeight - 44 * 2 - 10;
                                    jq("#detailContent").css({
                                        "height":h+'px'
                                    });
                                };
                                jq('#sel0').on('click',function () {
                                    tabSeleted(0);
                                });
                                jq('#sel1').on('click',function () {
                                    tabSeleted(1);
                                });
                                function tabSeleted(type) {
                                    jq("#detailContent").empty();
                                    detailType = type;
                                    if (type == 0){//0:详情介绍 1:用户评价
                                        jq("#sel0").addClass('selectedTextColor');
                                        jq("#sel1").removeClass('selectedTextColor');
                                        loadDetailPage();
                                    }else {
                                        jq("#sel1").addClass('selectedTextColor');
                                        jq("#sel0").removeClass('selectedTextColor');
                                        function loadEvaluatePage() {
                                            if (evaluatePage){
                                                jq("#detailContent").html(evaluatePage);
                                            }else {
                                                sendRequest("getBlissEvaluate",{"type":indexParams.type},function (data) {
                                                   prepareEvaluatePage(data);
                                                });
                                                if (localDebug == true){
                                                    getJsonData("evalute.json",function (data) {
                                                        prepareEvaluatePage(data);
                                                    });
                                                }
                                                function prepareEvaluatePage(data) {
                                                    arr = data;
                                                    if(arr.length > 0 && arr != undefined){
                                                        var evaluteList = '<div class="contentView evaluateContent"> <ul id="evaluteList" class="mui-table-view">';
                                                        jq.each(arr,function (idx,item) {
                                                            var picUrl = '';
                                                            if (!(item["picurl"] == null || item["picurl"] == undefined)){
                                                                picUrl = item["picurl"];
                                                            }
                                                            var cell = '<li class="mui-table-view-cell normalBottom"> <div class="evaluateTop"> <img class="userIcon" src="'+picUrl+'" alt="头像"> <div class="phone">'+hidePhone(item["phone"])+'</div> <div class="evaluateStarContent"> ';
                                                            for (var i = 0;i<item["evaluateNum"];i++){
                                                                cell = cell + '<img src="img/evaluteStar.png" class="star">'
                                                            }
                                                            cell = cell + '</div> </div> <div class="evaluate">'+item["evaluateContent"]+'</div> <div class="date">'+formateDate(item["createdTime"])+'</div> </li>';
                                                            evaluteList = evaluteList + cell;
                                                        });
                                                        evaluatePage = evaluteList + '</ul></div>';
                                                        if (type == 1){
                                                            jq("#detailContent").html(evaluatePage);
                                                        }
                                                    }else {

                                                        jq("#detailContent").html('<dic class="evaluateEmptyPage"> <img src="img/icon_empty.png"/><p>暂无评论</p></dic>');
                                                    }
                                                }

                                            }
                                        }
                                        loadEvaluatePage();

                                    }
                                }
                            }
                        })

                    })
                })
            })
        })
    });
}
indexJsLoad();

